package com.infore.airsupervise.http;

import android.content.Intent;

import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.MyApplication;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.UserE;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 请求回调：统一回调处理
 *
 * @author: dingxinlin
 * @date: 2016-11-22 14:34
 */

public class HttpCallBack implements Callback<BaseResponse> {

    @Override
    public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
        // 状态码
        int statusCode = response.raw().code();
        // 服务器正常
        if (statusCode== StatusConst.CODE_STATUS_OK && response.body() != null) {
            int opCode = response.body().getStatus();
            switch (opCode) {
                case StatusConst.CODE_OPERATION_FAIL:
                    onFailed(opCode, response.body().getMessage());
                    break;
                case StatusConst.CODE_OPERATION_OUTLINE:
                    onOutLine(opCode,response.body().getMessage());
                    call.cancel();
                    break;
                default:
                    onSuccess(opCode, response.body());
                    break;
            }
        }
        // 服务器异常
        else {
            onException(StatusConst.CODE_SERVER_EXCEPTION, MsgConst.SERVER_WRONG, MsgConst.PLEASE_TRY_LATER);
        }
    }

    @Override
    public void onFailure(Call<BaseResponse> call, Throwable t) {
        try {
            throw t;
        } catch (ConnectException throwable) {
            onException(StatusConst.CODE_CONNECT_FAIL, MsgConst.CONNECT_WRONG, MsgConst.PLEASE_CHECK_NETWORK);
        } catch (SocketTimeoutException throwable) {
            onException(StatusConst.CODE_CONNECT_TIMEOUT, MsgConst.TIME_OUT, MsgConst.PLEASE_CHECK_NETWORK);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    /*
     * 请求正常、服务器处理成功
     */
    public void onSuccess(int operationCode, BaseResponse response) {
    }

    /*
     * 请求正常、服务器处理失败
     */
    public void onFailed(int operationCode, String desc) {
    }

    /*
     * 请求异常
     */
    public void onException(int errorCode, String title, String desc) {
    }

    /*
     * 登录状态超时
     */
    public void onOutLine(int operationCode, String desc){
        /**
         * 发送重新登录的广播
         */
        UserE.cleanLoginInfo();
        Intent it= new Intent();
        it.setAction(Constants.ACTION_INTENT_RELOGIN);
        MyApplication.getInstance().sendBroadcast(it);
    }
}
